<template>
  <div ref="chartRef" :style="{ width: '100%', height: '100%' }"></div>
</template>

<script setup lang="ts">
import { ref, watchEffect, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
const chartRef = ref(null)
let chartInstance = null as any
const props = defineProps({
  options: {
      type: Object,
      default:{},
      required: true
    }
})
// 初始化Echarts实例
const initChart = () => {
  if (!chartRef.value) return
  chartInstance = echarts.init(chartRef.value)
  chartInstance.setOption(props.options)
}

// 自适应大小
const resizeChart = () => {
  chartInstance && chartInstance.resize()
}

// 监听组件宽高的变化
watchEffect(() => {
  resizeChart()
})

// 监听options的变化
watchEffect(() => {
  chartInstance && chartInstance.setOption(props.options)
})

// 在组件挂载时初始化Echarts实例
onMounted(() => {
  initChart()
  window.addEventListener('resize', resizeChart)
})

// 在组件卸载时销毁Echarts实例
onUnmounted(() => {
  chartInstance && chartInstance.dispose()
  chartInstance = null
  window.removeEventListener('resize', resizeChart)
})
</script>
